package org.example.java.jvm.gc;

/**
 * -XX:+PrintGCDetails
 */
public class FinalizeEscapeGc {
  private byte[] data = new byte[1024 * 1024 * 1];
  protected int count = 0;
  private static FinalizeEscapeGc fec = new FinalizeEscapeGc();

  public FinalizeEscapeGc() {
  }

  public static void main(String[] args) throws InterruptedException {
    //对象第一次成功拯救自己
    fec = null;
    System.gc();
    //显然输出为null
    System.out.println(fec);
    //因为finalize优先级很低，暂停一秒，以等待它
    Thread.sleep(1000);
    //打印x.FinalizeEscapeGc@c17164，说明成功拯救
    System.out.println(fec);

    //第二次次拯救失败
    fec = null;
    //显然输出为null
    System.out.println(fec);

    System.gc();
    //因为finalize优先级很低，暂停一秒，以等待它
    Thread.sleep(1000);
    //输出为null
    System.out.println(fec);
  }

  @Override
  public void finalize() throws Throwable {
    super.finalize();
    System.out.println("执行finalize方法");
    fec = this;
  }

  public int getCount() {
    return count;
  }
}
